package com.ilop.sthome.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.alink.linksdk.channel.mobile.api.IMobileDownstreamListener;
import com.aliyun.alink.linksdk.channel.mobile.api.MobileChannel;
import com.example.common.base.OnCallBackToRefresh;
import com.example.common.utils.MediaPlayerUtil;
import com.ilop.sthome.app.MyApplication;
import com.ilop.sthome.common.CommandHandler;
import com.ilop.sthome.common.command.SendDeviceCommand;
import com.ilop.sthome.common.udp.ControllerUdpHelper;
import com.ilop.sthome.common.udp.GatewayUdpUtil;
import com.ilop.sthome.common.udp.OnUdpReceiveCallBack;
import com.ilop.sthome.data.enums.NetworkType;
import com.ilop.sthome.data.greenDao.DeviceInfoBean;
import com.ilop.sthome.ui.dialog.BaseDialog;
import com.ilop.sthome.utils.greenDao.utils.DeviceDaoUtil;
import com.ilop.sthome.utils.system.NetStateChangeObserver;
import com.ilop.sthome.utils.system.NetStateChangeReceiver;
import com.siterwell.familywellplus.R;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author skygge
 * @date 2019-12-23.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：SiterService服务
 */
public class SiterService extends Service implements NetStateChangeObserver {

    private final String TAG = this.getClass().getName();
    private ExecutorService mExecutorService;
    private Handler mHandler;
    private BaseDialog mDialog;

    @Override
    public void onCreate() {
        mExecutorService = Executors.newFixedThreadPool(7);
        mHandler = new Handler();
        MobileChannel.getInstance().registerDownstreamListener(true, mDownStreamListener);
        ControllerUdpHelper.getInstance().onStartConnection(this);
        ControllerUdpHelper.getInstance().registerUdpReceiveCallBack(mUdpReceiveCallBack);
        NetStateChangeReceiver.registerReceiver(this);
        NetStateChangeReceiver.registerObserver(this);
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new Binder();
    }

    private IMobileDownstreamListener mDownStreamListener = new IMobileDownstreamListener() {
        @Override
        public void onCommand(String method, String data) {
            Log.d(TAG, "接收数据-TCP" + data);
            doDealTcpData(data);
        }

        @Override
        public boolean shouldHandle(String method) {
            return true;
        }
    };

    private OnUdpReceiveCallBack mUdpReceiveCallBack = new OnUdpReceiveCallBack() {
        @Override
        public void receiveData(String deviceName, String msg) {
            Log.d(TAG, "接收数据-UDP" + msg);
            doDealUdpData(deviceName, msg);
        }

        @Override
        public void receiveAnswer(String deviceName) {
            Log.d(TAG, "UDP应答" + deviceName);
            ControllerUdpHelper.getInstance().onSendUdpAnswer(deviceName);
        }
    };

    /**
     * 处理UDP数据
     * @param data 设备上报数据
     */
    private void doDealUdpData(String deviceName, String data) {
        try {
            JSONObject jsonObject = JSON.parseObject(data);
            JSONObject jsonObject1 = jsonObject.getJSONObject("msg");
            if (jsonObject1!=null){
                CommandHandler command = new CommandHandler(this, deviceName, jsonObject1, mHandler);
                command.onAlarmCallBack(this::sendAlarmDialog);
                mExecutorService.execute(command);
            }
        }catch (Exception e) {
            e.printStackTrace();
            ControllerUdpHelper.getInstance().unRegisterUdpReceiveCallBack();
        }
    }

    /**
     * TCP处理数据
     * @param data 设备上报数据
     */
    private void doDealTcpData(String data){
        try {
            JSONObject jsonObject = JSON.parseObject(data);
            String deviceName = jsonObject.getString("deviceName");
            if (GatewayUdpUtil.getInstance().isGatewayIntranet(deviceName)){
                Log.d(TAG, "接收数据-TCP 内网在线");
                return;
            }
            JSONObject value = jsonObject.getJSONObject("value");
            if (value!=null){
                CommandHandler command = new CommandHandler(this, deviceName, value, mHandler);
                command.onAlarmCallBack(this::sendAlarmDialog);
                mExecutorService.execute(command);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 弹出框
     * @param deviceName 网关
     * @param title 标题
     * @param isAlarm 低电压或离线（隐藏静音）
     */
    private void sendAlarmDialog(String deviceName, String title, boolean isAlarm){
        mHandler.post(()-> {
            if (mDialog == null || !mDialog.isShowing()){
                MediaPlayerUtil mMediaPlayer = new MediaPlayerUtil(MyApplication.getCurActivity());
                mMediaPlayer.playAlarm();
                mDialog = new BaseDialog(MyApplication.getCurActivity(), new OnCallBackToRefresh() {
                    @Override
                    public void onConfirm() {
                        mMediaPlayer.destroy();
                        DeviceInfoBean deviceInfoBean = DeviceDaoUtil.getInstance().findGatewayByDeviceName(deviceName);
                        if(deviceInfoBean!=null){
                            SendDeviceCommand sendDeviceCommand = new SendDeviceCommand(MyApplication.getCurActivity(), deviceInfoBean);
                            sendDeviceCommand.sendGateWaySilence();
                        }
                    }

                    @Override
                    public void onCancel() {
                        mMediaPlayer.destroy();
                    }
                });
                if (!isAlarm){
                    mDialog.setCancelVisibility(true);
                    mDialog.setMsg(title);
                    mDialog.setCancelText(MyApplication.getCurActivity().getString(R.string.initialzation_guidance_button));
                }else {
                    mDialog.setTitleAndButton(title, MyApplication.getCurActivity().getString(R.string.cancel), MyApplication.getCurActivity().getString(R.string.silence));
                }
                mDialog.show();
            }
        });
    }

    @Override
    public void onNetDisconnected() {
        Log.e(TAG, "startConfig: 网络断开");
        MobileChannel.getInstance().unRegisterDownstreamListener(mDownStreamListener);
        ControllerUdpHelper.getInstance().unRegisterUdpReceiveCallBack();
    }

    @Override
    public void onNetConnected(NetworkType networkType) {
        Log.i(TAG, "startConfig: 网络连接" + networkType.toString());
        MobileChannel.getInstance().registerDownstreamListener(true, mDownStreamListener);
        if (networkType != NetworkType.NETWORK_WIFI){
            GatewayUdpUtil.getInstance().setAllGatewayOffLine();
        }
    }


    @Override
    public void onDestroy(){
        if (mExecutorService!=null && !mExecutorService.isShutdown()){
            mExecutorService.isShutdown();
        }
        MobileChannel.getInstance().unRegisterDownstreamListener(mDownStreamListener);
        ControllerUdpHelper.getInstance().unRegisterUdpReceiveCallBack();
        NetStateChangeReceiver.unRegisterObserver(this);
        NetStateChangeReceiver.unRegisterReceiver(this);
    }
}